<?php

namespace app\api\controller;

use app\facade\Redis;
use think\Validate;
use app\facade\Mns;
use app\models\{BusinessCommu, Cart, BusinessType, AgentCommu, Recpeople, Region, PlatClass, PlatSons, Banner, Goods, Business, GoodsSpec, BusinessArea, Compent, UserLevel, Wechat, Config, ConvenClass, Conven, Agent, Address, Order, OrderGoods};
use think\facade\Env;
use think\Db;
use think\facade\Log;

use oss\Oss;
use think\db\Where;
use EasyWeChat\Factory;


class Other extends Base
{

    public function getfjxiaoqu()
    {
        $lat = $this->request->get('lat/d', 0);
        $lon = $this->request->get('lon/d', 0);
        $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $list = (new AgentCommu())
            ->field('id,name,address,' . $filed)
            ->limit(15)
            ->order('dist asc')
            ->where('status', 1)
            ->select();
        $this->result($list, 0, '获取成功');
    }

    public function getxiaoqu()
    {
        $xiaoquid = $this->request->get('xiaoquid/d', 0);
        $list = (new AgentCommu())->where(['id' => $xiaoquid, 'status' => 1])->find();
        if (empty($list)) {
            $this->result([], 1, '获取失败');
        }
        $list['ruzhu'] = 2;
        $this->result($list, 0, '获取成功');
    }

    public function businesscate()
    {
        $businessid = $this->request->get('businessid/d', 0);
        $keyword = $this->request->get('keyword');
        $list =  (new PlatClass())
            ->order(['sort' => 'desc', 'id' => 'asc'])
            ->where(['isshow' => 1, 'businessid' => $businessid, 'type' => 2])->field('id,name');
        $list = $list->select();
        $user_id = $this->request->user_id ? $this->request->user_id : 0;
        $result = [];
        //全部产品
        $productss = (new Goods())->alias('g')
            ->order(['g.sorts' => 'desc', 'g.id' => 'desc'])
            ->where(['g.isdel' => 1, 'g.isSale' => 1, 'g.businessid' => $businessid]);
        if (!empty($keyword)) {
            $productss = $productss->where('g.title', 'like', '%' . $keyword . '%');
        }
        $productss = $productss->select();
        foreach ($productss as $good) {
            //查询所有评价
            $pj = (new Compent())->where('goodsid', $good['id'])->count();
            if ($pj > 0) {
                $good['goodspj'] = floor($good['goodspj'] * 10000 / $pj) / 100;
            } else {
                $good['goodspj'] = 100;
            }
            $good['goodspj'] = $good['goodspj'] > 100 ? 100 : $good['goodspj'];
            $good['images'] = json_decode($good['images'], true);
            $goodsspec = (new GoodsSpec())->field('id,price,name,stock,unmit')->where(['isdel' => 1, 'goodid' => $good['id']])->order('is_default desc')->select();
            foreach ($goodsspec as $spec) {
                $spec['number'] = (new Cart())->where(['specid' => $spec['id'], 'user_id' => $user_id])->value('number') ?? 0;
                if ($spec['number'] < $good['starbuy']) {
                    $spec['number'] = $good['starbuy'];
                }
                if (empty($spec['number'])) {
                    $spec['number'] = 1;
                }
            }
            $good['goodspec'] = $goodsspec;
        }
        $result[0] = [
            'id' => 0,
            'name' => '全部产品',
            'images' => '',
            'product' => $productss
        ];
        foreach ($list as $k => $row) {
            $product =  (new Goods())->alias('g')
                ->order(['g.sorts' => 'desc', 'g.id' => 'desc'])
                ->where(['g.isdel' => 1, 'g.isSale' => 1, 'g.businessid' => $businessid, 'g.classid' => $row['id']])
                ->select();
            foreach ($product as $good) {
                //查询所有评价
                $pj = (new Compent())->where('goodsid', $good['id'])->count();
                if ($pj > 0) {
                    $good['goodspj'] = floor($good['goodspj'] * 10000 / $pj) / 100;
                } else {
                    $good['goodspj'] = 100;
                }
                $good['goodspj'] = $good['goodspj'] > 100 ? 100 : $good['goodspj'];
                $good['images'] = json_decode($good['images'], true);
                $goodsspec = (new GoodsSpec())->field('id,price,name,stock,unmit')->where(['isdel' => 1, 'goodid' => $good['id']])->order('is_default desc')->select();
                foreach ($goodsspec as $spec) {
                    $spec['number'] = (new Cart())->where(['specid' => $spec['id'], 'user_id' => $user_id])->value('number') ?? 0;
                    if ($spec['number'] < $good['starbuy']) {
                        $spec['number'] = $good['starbuy'];
                    }
                    if (empty($spec['number'])) {
                        $spec['number'] = 1;
                    }
                }
                $good['goodspec'] = $goodsspec;
            }
            $row['product'] = $product;
            $result[$k + 1] = $row;
        }
        $this->result($result, 0, '获取成功');
    }

    public function getgoodlist()
    {
        $businessid = $this->request->get('shopid/d', 0);
        $isSale = $this->request->get('isshow/d', 1);
        $classid = $this->request->get('cate/d', 0);
        $sonsid = $this->request->get('sonscate/d', 0);
        $title = $this->request->get('title', '');
        $sorts = $this->request->get('sorts/d', 0);

        $list = (new Goods())
            ->alias('g')
            ->distinct(true)
            ->field('g.id,g.title,g.images,g.recomm,g.descs,g.sale,g.isSale')
            ->where(['b.id' => $businessid, 'g.isdel' => 1])
            ->join('business b', 'g.businessid= b.id');
        if (!empty($isSale)) {
            $list = $list->where('g.isSale', $isSale);
        }
        if (!empty($sorts)) {
            $list = $list->order('id desc');
        } else {
            $list = $list->order('recomm desc');
        }
        if (!empty($classid)) {
            $list = $list->where('g.classid', $classid);
        }
        if (!empty($sonsid)) {
            $list = $list->where('g.sonsid', $sonsid);
        }
        if (!empty($title)) {
            $list = $list->where('g.title', 'like', "%" . $title . "%");
        }
        $list = $list->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $good) {
            $good['images'] = json_decode($good['images'], true);
            $good['goodspec'] = (new GoodsSpec())->field('id,price,name,stock,unmit')->where(['isdel' => 1, 'goodid' => $good['id']])->order('is_default desc')->select();
        }
        $this->result($list, 0, '获取成功');
    }

    public function getrecomm()
    {
        $xiaoquid = $this->request->get('xiaoquid/d', 0);
        $businessid = (new BusinessCommu())->where('status', 1)->where('commuid', $xiaoquid)->column('businessid') ?? [];
        if (empty($businessid)) {
            $businessid = [0];
        }
        $list = (new Goods())
            ->alias('g')
            ->distinct(true)
            ->order('recomm desc')
            ->field('g.id,g.title,g.images,g.recomm,g.descs,g.sale,g.goodspj')
            ->where(['b.id' => $businessid, 'b.status' => 1, 'b.type' => 1])
            ->join('business b', 'g.businessid= b.id')->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $good) {
            //查询所有评价
            $pj = (new Compent())->where('goodsid', $good['id'])->count();
            if ($pj > 0) {
                $good['goodspj'] = floor($good['goodspj'] * 10000 / $pj) / 100;
            } else {
                $good['goodspj'] = 100;
            }
            $good['goodspj'] = $good['goodspj'] > 100 ? 100 : $good['goodspj'];
            $good['images'] = json_decode($good['images'], true);
            $good['goodspec'] = (new GoodsSpec())->field('id,price,name,stock,unmit')->where(['isdel' => 1, 'goodid' => $good['id']])->order('is_default desc')->select();
        }
        $this->result($list, 0, '获取成功');
    }

    public function getbusiness()
    {
        $type = $this->request->get('type/d', 1);
        $xiaoquid = $this->request->get('xiaoquid/d', 0);
        $businessid = (new BusinessCommu())->where('status', 1)->where('commuid', $xiaoquid)->column('businessid') ?? [];
        if (empty($businessid)) {
            $businessid = [0];
        }
        $list = [];
        if ($type == 1) {
            $list = (new BusinessType())->where(['ishot' => 2, 'status' => 1])->select();
            foreach ($list as $row) {
                $business = (new Business())->limit(5)->field('b.id,b.title,b.address,b.logo,b.sends,b.sendmoney')->alias('b')->where(['b.status' => 1, 'b.type' => 2, 'b.sonstype' => $row['id'], 'b.id' => $businessid])->select();
                foreach ($business as $bus) {
                    $star = (new Compent())->where('businessid', $bus['id'])->avg('star');
                    if (empty($star)) {
                        $bus['star'] = 5;
                    } else {
                        $bus['star'] = $star <= 3 ? 4 : 5;
                    }
                    $bus['sales'] = (new Goods())->where('businessid', $bus['id'])->sum('sale');
                    $bus['sends'] = (float)$bus['sends'];
                    $bus['sendmoney'] = (float)$bus['sendmoney'];
                }
                $row['business'] = $business;
            }
            $this->result($list, 0, '获取成功');
        } else {
            $sales = $this->request->get('sales/d', 0);
            $cate = $this->request->get('cate/d', 0);
            $keyword = $this->request->get('keyword', '');
            $cates = (new BusinessType())->order('ishot desc')->where(['status' => 1])->select();
            $catelist = [];
            foreach ($cates as $ca) {
                $catelist[] = [
                    'label' => $ca['name'],
                    'value' => $ca['id']
                ];
            }
            $list = (new Business())->limit(10)->field('b.id,b.title,b.address,b.logo,b.sends,b.sendmoney');
            $list = $list->where(['b.id' => $businessid]);
            if (!empty($sales) && $sales == 1) {
                $list = $list->order(['b.sale' => 'desc']);
            }
            if (!empty($sales) && $sales == 2) {
                $list = $list->order(['b.sendmoney' => 'asc']);
            }
            if (!empty($sales) && $sales == 3) {
                $list = $list->order(['b.sends' => 'asc']);
            }
            if (!empty($cate)) {
                $list = $list->where(['b.sonstype' => $cate]);
            }
            if (!empty($keyword)) {
                $list = $list->where('b.title', 'like', '%' . $keyword . '%');
            }
            $list = $list->where(['b.status' => 1, 'b.type' => 2])->alias('b')->paginate(20, false, ['query' => $this->request->param()]);
            foreach ($list as $bus) {
                $star = (new Compent())->where('businessid', $bus['id'])->avg('star');
                if (empty($star)) {
                    $bus['star'] = 5;
                } else {
                    $bus['star'] = $star <= 3 ? 4 : 5;
                }
                $bus['sales'] = (new Goods())->where('businessid', $bus['id'])->sum('sale');
                $bus['sends'] = (float)$bus['sends'];
                $bus['sendmoney'] = (float)$bus['sendmoney'];
                $goods = (new Goods())->order(['recomm' => 'desc', 'sale' => 'desc'])->where(['businessid' => $bus['id'], 'isSale' => 1, 'isdel' => 1])->limit(3)->select();
                foreach ($goods as $good) {
                    $good['images'] = json_decode($good['images'], true) ?? [];
                    $good['price'] = (new GoodsSpec())->order('is_default desc')->where('goodid', $good['id'])->value('price') ?? 0;
                }
                $bus['goods'] = $goods;
            }
            $this->result(['list' => $list, 'cate' => $catelist], 0, '获取成功');
        }
    }

    public function getagentcommu()
    {
        $lat = $this->request->get('lat/d', 0);
        $lon = $this->request->get('lon/d', 0);
        $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $result = (new AgentCommu())->field('*,' . $filed)->order('dist asc')->find();
        $this->result($result, 0, '获取成功');
    }

    public function getptdatas()
    {
        $ptdatas = (new Config())->where('name', 'ptdatas')->value('value');
        $ptdatas = json_decode($ptdatas, true);
        if (!empty($ptdatas['orderuser'])) {
            unset($ptdatas['orderuser']);
        }
        $ptdatas['userlists'] = [];
        $lists = Redis::lRange('ptdatas_lists', 0, 30);
        foreach ($lists as $list) {
            $ptdatas['userlists'][] = unserialize($list);
        }
        $this->result($ptdatas, 0, '获取成功');
    }

    public function getopenid()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'id' => 'require',
            'state' => 'require'
        ], [
            'id.require' => 'ID不能为空',
            'state.require' => '类型必须填写',
        ]);
        if (!$validate->check($data)) {
            $results = ['status' => 1, 'info' => $validate->getError()];
            return view(null, ['list' => $results]);
        }
        $config = config('wechat2.');
        try {
            $app = Factory::officialAccount($config);
            $wxuser = $app->oauth->user();
            if (empty($wxuser['id'])) {
                $results = ['status' => 1, 'info' => '授权失败,请重试'];
                return view(null, ['list' => $results]);
            }
            if ($data['state'] == 1) {
                $business = (new Business())->where('id', $data['id'])->find();
                if (empty($business)) {
                    $results = ['status' => 1, 'info' => '授权失败,商家不存在'];
                    return view(null, ['list' => $results]);
                }
                if (!empty($business['openid'])) {
                    $results = ['status' => 1, 'info' => '授权失败,请先解绑授权'];
                    return view(null, ['list' => $results]);
                }
                if ($business['openid'] == $wxuser['id']) {
                    $results = ['status' => 0, 'info' => '授权成功，您已订阅公众号订单通知服务!'];
                    return view(null, ['list' => $results]);
                }
                $res = (new Business())->where('id', $data['id'])->update(['openid' => $wxuser['id']]);
                if (!$res) {
                    $results = ['status' => 1, 'info' => '授权失败,请重试'];
                    return view(null, ['list' => $results]);
                }
            } elseif ($data['state'] == 2) {
                $business = (new Agent())->where('id', $data['id'])->find();
                if (empty($business)) {
                    $results = ['status' => 1, 'info' => '授权失败,商家不存在'];
                    return view(null, ['list' => $results]);
                }
                if (!empty($business['openid'])) {
                    $results = ['status' => 1, 'info' => '授权失败,请先解绑授权'];
                    return view(null, ['list' => $results]);
                }
                if ($business['openid'] == $wxuser['id']) {
                    $results = ['status' => 0, 'info' => '授权成功，您已订阅公众号订单通知服务!'];
                    return view(null, ['list' => $results]);
                }
                $res = (new Agent())->where('id', $data['id'])->update(['openid' => $wxuser['id']]);
                if (!$res) {
                    $results = ['status' => 1, 'info' => '授权失败,请重试'];
                    return view(null, ['list' => $results]);
                }
            } else {
                $results = ['status' => 1, 'info' => '授权失败,请重试'];
                return view(null, ['list' => $results]);
            }
        } catch (\Exception $e) {
            $results = ['status' => 1, 'info' => '授权失败,请重试'];
            return view(null, ['list' => $results]);
        }
        $message = [
            '测试信息',
            123456789,
            '测试信息',
            100,
            date('Y-m-d H:i:s')
        ];
        $this->wechattest($wxuser['id'], '您好，您负责区域有新的订单', $message, '【信息通知】');
        $results = ['status' => 0, 'info' => '授权成功，您已订阅公众号订单通知服务!'];
        return view(null, ['list' => $results]);
    }


    public function getOpenIds()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'code' => 'require',
            'mobile' => 'require'
        ], [
            'code.require' => 'code不能为空',
            'mobile.require' => '师傅端手机号不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Recpeople())->where(['mobile' => $data['mobile']])->find();
        $results = ['status' => 1, 'info' => '授权失败!'];
        if (empty($user)) {
            $results = ['status' => 1, 'info' => '账号不存在,请确保手机号码正确!'];
            return view(null, ['list' => $results]);
        }
        $config = config('wechat2.');
        $message = [
            '测试信息',
            123456789,
            '测试信息',
            100,
            date('Y-m-d H:i:s')
        ];
        try {
            $app = Factory::officialAccount($config);
            $wxuser = $app->oauth->user();
            if (!empty($wxuser['id'])) {
                if (!empty($user['openid']) && $user['openid'] == $wxuser['id']) {
                    $results = ['status' => 0, 'info' => '公众号订单通知服务订阅成功!(授权成功公众号会有测试信息)'];
                    $this->wechattest($wxuser['id'], '您好，您负责区域有新的订单', $message, '【师傅信息通知】');
                    return view(null, ['list' => $results]);
                }
                $res = (new Recpeople())->where(['id' => $user['id']])->update(['openid' => $wxuser['id']]);
                if (!$res) {
                    $results = ['status' => 1, 'info' => '授权失败!'];
                    return view(null, ['list' => $results]);
                }
            }
        } catch (\Exception $e) {
            $results = ['status' => 1, 'info' => '授权失败,请重试'];
            return view(null, ['list' => $results]);
        }
        $results = ['status' => 0, 'info' => '公众号订单通知服务订阅成功!(授权成功公众号会有测试信息)'];
        $this->wechattest($wxuser['id'], '您好，您负责区域有新的订单', $message, '【师傅信息通知】');
        return view(null, ['list' => $results]);
    }

    //订单通知
    public function wechattest($touser = '', $first = '', $data, $remark = '')
    {
        $config = config('wechat2.');
        $app = Factory::officialAccount($config);
        $send_data = [
            'template_id' => 'Mch9D2t3ckjmDI-s9zYbO9-LaVR_0kDwqeGwAcVXRkA', // 所需下发的订阅模板id
            'touser' => $touser,     // 接收者（用户）的 openid
            'miniprogram' => [
                'appid' => config('wechat.')['app_id'],
                'pagepath' => '/',
            ],
            'data' => [
                'first' => [
                    'value' => $first
                ],
                'keyword1' => [
                    'value' => $data[0] ?? ''
                ],
                'keyword2' => [
                    'value' =>  $data[1] ?? ''
                ],
                'keyword3' => [
                    'value' => $data[2] ?? ''
                ],
                'keyword4' => [
                    'value' =>  $data[3] ?? ''
                ],
                'keyword5' => [
                    'value' =>  $data[4] ?? ''
                ],
                'remark' => [
                    'value' => $remark
                ],
            ],
        ];
        $rm = $app->template_message->send($send_data);
    }

    public function convenclass()
    {
        $list = (new ConvenClass())->where('isshow', 1)->order(['sort' => 'desc'])->field('id,name')->select();
        $this->result($list, 0, '获取成功');
    }

    public function conven()
    {
        $streetid = $this->request->get('streetid/d', 0);
        $classid = $this->request->get('classid/d', 0);
        $lat = $this->request->get('lat/d', 0);
        $lon = $this->request->get('lon/d', 0);
        $business = getdrees($lat, $lon);
        dump($business);
        die;
        $street = (new Region())->where(['id' => $streetid, 'level' => 4])->find();
        $area = (new Region())->where(['area_code' => $street['area_code'], 'level' => 3])->find();
        $city = (new Region())->where(['id' => $area['parent_id'], 'level' => 2])->find();
        // $province = (new Region())->where(['id' => $city['parent_id'], 'level' => 1])->find();
        $where = [
            'type' => 1
        ];
        $where1 = [
            'type' => 2,
            'city' => $city['area_code'] ?? 0
        ];
        $where2 = [
            'type' => 3,
            'area' => $area['area_code'] ?? 0
        ];
        $where3 = [
            'type' => 4,
            'street' => $streetid ?? 0
        ];
        if (!empty($classid)) {
            $where['classid'] = $classid;
            $where1['classid'] = $classid;
            $where2['classid'] = $classid;
            $where3['classid'] = $classid;
        }
        $list = (new Conven())->whereOr(function ($query) use ($where) {
            $query->where($where);
        })->whereOr(function ($query) use ($where1) {
            $query->where($where1);
        })->whereOr(function ($query) use ($where2) {
            $query->where($where2);
        })->whereOr(function ($query) use ($where3) {
            $query->where($where3);
        })->field('id,title,mobile,address,contents')->select();
        $this->result($list, 0, '获取成功');
    }

    public function others()
    {
        $name = $this->request->get('name', '');
        $result = (new Config())->where('name', $name)->find();
        $this->result($result, 0, '获取成功');
    }

    //回调结果
    public function callback()
    {

        $result = (new Wechat())->callback();
        if ($result['msg'] == 'success') {
            return true;
        }
        return false;
    }

    //回调结果
    public function callback2()
    {
        $result = (new Wechat())->callback2();
        if ($result['msg'] == 'success') {
            return true;
        }
        return false;
    }

    public function business()
    {
        $businessid = $this->request->get('businessid/d', 0);
        $cate = $this->request->get('cate/d', 0);
        $list = (new Business())->where('id', $businessid)->field('account,password,money,created', true)->find();
        if ($list) {
            $star = (new Compent())->where('businessid', $list['id'])->avg('star');
            if (empty($star)) {
                $list['star'] = 5;
            } else {
                $list['star'] = $star <= 3 ? 4 : 5;
            }
            $list['images'] = json_decode($list['images'], true) ?? [];
            $list['yyzz'] = json_decode($list['yyzz'], true) ?? [];
            $list['sales'] = (new Goods())->where('businessid', $list['id'])->sum('sale');
            $list['sends'] = (float)$list['sends'];
            $list['sendmoney'] = (float)$list['sendmoney'];
            $list['leimu'] = (new businessType())->where('id', $list['sonstype'])->value('name') ?? '';
            if ($cate == 1) {
                $catelist = [];
                $catelist[] = [
                    'value' => 0,
                    'label' => '全部',
                ];
                //上门服务商
                if ($list['type'] == 1) {
                    $platclass = (new PlatClass())->where(['type' => [1, 3], 'businessid' => [0, $list['id']], 'isshow' => 1])->select();
                } elseif ($list['type'] == 2) {
                    $platclass = (new PlatClass())->where(['type' => 2, 'businessid' => $list['id'], 'isshow' => 1])->select();
                } else {
                    $platclass = [];
                }
                foreach ($platclass as $class) {
                    $rowcate = [
                        'value' => $class['id'],
                        'label' => $class['name'],
                    ];
                    if ($list['type'] == 1) {
                        $rowcate['children'] = [];
                        $rowcate['children'][] = [
                            'value' => 0,
                            'label' => '全部',
                        ];
                        $platsons = (new PlatSons())->where(['platclassid' => $class['id'], 'isshow' => 1])->select();
                        foreach ($platsons as $sons) {
                            $rowcate['children'][] = [
                                'value' => $sons['id'],
                                'label' => $sons['name'],
                            ];
                        }
                    }

                    $catelist[] = $rowcate;
                }
                $list['catelist'] = $catelist;
            } elseif ($cate == 2) {
                $catelist = [];
                //上门服务商
                if ($list['type'] == 1) {
                    $platclass = (new PlatClass())->where(['type' => [1, 3], 'businessid' => [0, $list['id']], 'isshow' => 1])->select();
                } elseif ($list['type'] == 2) {
                    $platclass = (new PlatClass())->where(['type' => 2, 'businessid' => $list['id'], 'isshow' => 1])->select();
                } else {
                    $platclass = [];
                }
                foreach ($platclass as $class) {
                    $rowcate = [
                        'value' => $class['id'],
                        'label' => $class['name']
                    ];
                    if ($list['type'] == 1) {
                        $rowcate['children'] = [];
                        $platsons = (new PlatSons())->where(['platclassid' => $class['id'], 'isshow' => 1])->select();
                        foreach ($platsons as $sons) {
                            $rowcate['children'][] = [
                                'value' => $sons['id'],
                                'label' => $sons['name'],
                            ];
                        }
                    }

                    $catelist[] = $rowcate;
                }
                $list['catelist'] = $catelist;
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function user_level()
    {
        $level = $this->request->get('level/d', 1);
        $result = (new UserLevel())->where('level', $level)->find();
        if ($result) {
            $result['coupon'] = json_decode($result['coupon'], true);
        }
        $this->result($result, 0, '获取成功');
    }

    public function oss()
    {
        // if (empty($_FILES['file'])) {
        //     $this->result([], 1, '参数错误');
        // }
        if ($this->request->isPost()) {
            $file = request()->file('file');
            $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/";
            $info = $file->validate(['size' => 1024 * 1024 * 5, 'ext' => 'jpg,png,gif,jpeg'])
                ->move($path);
            if (!$info) {
                $this->result([], 1, $file->getError());
            } else {
                $url = '/uploads' . '/' . date("Ymd") . '/' . $info->getfileName();
                $url = url($url, '', '', false);
                $url = "https://" . Env('app.api_url') . $url;
                $this->result($url, 0, '获取成功');
            }
        }
        // $file = $_FILES['file'];
        // $oss = new Oss();
        // $oss->setUploadType('ram');
        // $url = $oss->uploadPostFile($file, 'ming_user/' . date('Y-m-d'));
        // $this->result($url, 0, '获取成功');
        // $result = [];
        // try {
        //     $result = (new Oss())->getCredentials();
        //     $result['regionId'] = Env::get('aliyun.regionId');
        //     $result['bucket'] = Env::get('aliyun.bucket');
        //     $result['endpoint'] = Env::get('aliyun.endpoint');
        // } catch (\Exception $e) {
        //     $this->result([], 1, $e->getMessage());
        // }
        // $this->result($result, 0, '获取成功');
    }

    //高德接口
    public function getstreet()
    {
        $key = env('map.key');
        if ($this->request->isGet()) {
            $data = $this->request->get();
            Log::write($data, 'getstreet');
            $validate = new Validate([
                'lat' => 'require',
                'lng' => 'require',
            ], [
                'lat.require' => '纬度必须填写',
                'lng.require' => '经度必须填写',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $url = 'https://restapi.amap.com/v3/geocode/regeo';
            $res = api_curl($url, ['location' => $data['lng'] . ',' . $data['lat'], 'key' => $key, 'extensions' => 'all']);
            if ($res['status'] == 1) {
                if (empty($res['regeocode']['addressComponent'])) {
                    $this->result([], 1, '请求失败');
                }
                $results = $res['regeocode']['addressComponent'];
                $resuls = [
                    "adcode" => $results['adcode'] ?? 0,
                    "province" => $results['province'] ?? '',
                    "city" => $results['city'] ?? '',
                    "district" => $results['district'] ?? '',
                    "street" => 0,
                    "street_title" => $results['township'] ?? '',
                    'address' => $res['regeocode']['aois'][0]['name'] ?? '',
                    'formatted_address' => $res['regeocode']['formatted_address'] ?? ''
                ];
                $resuls['city'] = empty($resuls['city']) ? $resuls['province'] : $resuls['city'];
                $street_id = (new Region())
                    ->where(['level' => 4])
                    ->where('area_code', $resuls['adcode'])
                    ->where('name|remark', 'like', '%' . $resuls['street_title'] . '%')->find();
                //通过名字查找不到街道再通过编号查找
                if (empty($street_id['id'])) {
                    $street_id = (new Region())
                        ->where(['level' => 4])
                        ->where('area_code', $resuls['adcode'])
                        ->where('code', substr($results['towncode'], 0, 9))->find();
                }
                $resuls['street'] = $street_id['id'] ?? 0;
                $resuls['street_title'] = $street_id['name'] ?? $resuls['street_title'];
                $this->result($resuls, 0, '获取成功');
            } else {
                $this->result([], 1, '请求失败');
            }
        } else {
            $this->result([], 0, ['key' => $key]);
        }
    }
    //高德接口
    public function mygetstreet($data)
    {
        $key = env('map.key');
        $validate = new Validate([
            'lat' => 'require',
            'lng' => 'require',
        ], [
            'lat.require' => '纬度必须填写',
            'lng.require' => '经度必须填写',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $url = 'https://restapi.amap.com/v3/geocode/regeo';
        $res = api_curl($url, ['location' => $data['lng'] . ',' . $data['lat'], 'key' => $key, 'extensions' => 'all']);
        if ($res['status'] == 1) {
            if (empty($res['regeocode']['addressComponent'])) {
                return 0;
            }
            $results = $res['regeocode']['addressComponent'];
            $resuls = [
                "adcode" => $results['adcode'] ?? 0,
                "province" => $results['province'] ?? '',
                "city" => $results['city'] ?? '',
                "district" => $results['district'] ?? '',
                "street" => 0,
                "street_title" => $results['township'] ?? '',
                'address' => $res['regeocode']['aois'][0]['name'] ?? '',
                'formatted_address' => $res['regeocode']['formatted_address'] ?? ''
            ];
            $resuls['city'] = empty($resuls['city']) ? $resuls['province'] : $resuls['city'];
            $street_id = (new Region())
                ->where(['level' => 4])
                ->where('area_code', $resuls['adcode'])
                ->where('name|remark', 'like', '%' . $resuls['street_title'] . '%')->find();
            //通过名字查找不到街道再通过编号查找
            if (empty($street_id['id'])) {
                $street_id = (new Region())
                    ->where(['level' => 4])
                    ->where('area_code', $resuls['adcode'])
                    ->where('code', substr($results['towncode'], 0, 9))->find();
            }
            $resuls['street'] = $street_id['id'] ?? 0;
            $resuls['street_title'] = $street_id['name'] ?? $resuls['street_title'];
            return $resuls['street'];
        } else {
            return 0;
        }
    }

    public function street()
    {
        $areacode = $this->request->get('areacode/d', 0);
        $list = (new Region())->where('area_code', $areacode)->where(['level' => 4])->select();
        $this->result($list, 0, '获取成功');
    }

    public function addressjson()
    {
        $addressjsonredis = 'addressjsonredis';
        $haveaddress = Redis::get($addressjsonredis);
        if ($haveaddress) {
            $result = unserialize($haveaddress);
        } else {
            $region = (new Region())->field('name as label,area_code as value,id,parent_id,level')->where(['level' => [1, 2, 3]])->select();
            $resultson = [];
            $results = [];
            $result = [];
            foreach ($region as $regions) {
                if ($regions['level'] == 3) {
                    $resultson[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value']
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 2) {
                    $results[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $resultson[$regions['id']] ?? []
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 1) {
                    $result[] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $results[$regions['id']] ?? []
                    ];
                }
            }
            Redis::setex($addressjsonredis, 60 * 60 * 3, serialize($result));
        }
        return json($result);
    }

    public function getclass()
    {
        $getson = $this->request->get('getson/d', 2);
        $topid = $this->request->get('topid/d', 0);
        $type = $this->request->get('type/d', 1);
        $types = $this->request->get('types/d', 0);
        $xiaoquid = $this->request->get('xiaoquid/d', 0);
        if ($type == 3) {
            $list = (new PlatClass())->where(['isshow' => 1, 'type' => 3])->order('sort desc')->select();
            $row = [];
            foreach ($list as $lists) {
                $sons = (new PlatSons())->where('isshow', 1)->where('platclassid', $lists['id'])->field('created,platclassid,isshow', true)->order('sort desc')->select();
                foreach ($sons as $sons) {
                    $row[] = $sons;
                }
            }
            $this->result($row, 0, '获取成功');
        } elseif ($type == 5) {
            $businessid = (new BusinessCommu())->where('commuid', $xiaoquid)->where(['status' => 1])->column('businessid') ?? [];
            if (empty($businessid)) {
                $businessid = [0];
            }
            $list = (new PlatClass())->where(['isshow' => 1, 'type' => 3])->order('sort desc')->select();
            $results = [];
            foreach ($list as $lists) {
                $sons = (new PlatSons())->where('isshow', 1)->where('platclassid', $lists['id'])->field('created,platclassid,isshow', true)->order('sort desc')->select();
                foreach ($sons as $row) {
                    $row['spec'] = [];
                    $goods = (new Goods())->where(['businessid' => $businessid, 'sonsid' => $row['id']])->find();
                    if (empty($goods)) {
                        $goods = (new Goods())->order('sale desc')->where(['sonsid' => $row['id']])->find();
                    }
                    if (!empty($goods)) {
                        $goodsspec = (new GoodsSpec())->where('goodid', $goods['id'])->find();
                        if (empty($goods['starbuy']) || $goods['starbuy'] < 0) {
                            $number = 1;
                        } else {
                            $number = $goods['starbuy'];
                        }
                        if (!empty($goodsspec)) {
                            $row['spec'] = ['id' => $goodsspec['id'], 'number' => $number, 'price' => $goodsspec['price']];
                        }
                    }
                }
                $lists['sons']  = $sons;
                $results[] = $lists;
            }
            $this->result($results, 0, '获取成功');
        } else {
            $list = (new PlatClass())->where('isshow', 1)->field('created,isshow', true)->order('sort desc');
            if (!empty($topid)) {
                $list = $list->where('id', $topid);
            }
            if (!empty($types)) {
                $list = $list->where('types', $types);
            }
            if ($type == 4) {
                $list = $list->where(['type' => [1, 3], 'businessid' => 0]);
            } else {
                $list = $list->where('type', $type);
            }
            $list = $list->select();
            //获取下级子菜单
            $results = [];
            foreach ($list as $lists) {
                if ($getson == 1) {
                    $lists['sons'] = (new PlatSons())->where('isshow', 1)->where('platclassid', $lists['id'])->field('created,platclassid,isshow', true)->order('sort desc')->select();
                }
                if ($type == 2) {
                    $lists['types'] = 1;
                }
                $results[] = $lists;
            }
            $this->result($results, 0, '获取成功');
        }
    }

    public function getgoodsclass()
    {
        $xiaoquid = $this->request->get('xiaoquid/d', 0);
        $businessid = (new BusinessCommu())->where('commuid', $xiaoquid)->where(['status' => 1])->column('businessid') ?? [];
        if (empty($businessid)) {
            $businessid = [0];
        }
        $list = (new PlatClass())->where('isshow', 1)->where('ishot', 2)->where('type', 1)->field('created,sort,isshow', true)->order('sort desc')->select();
        foreach ($list as $lists) {
            $where = [
                'b.status' => 1,
                'g.businessid' => $businessid,
                'g.classid' => $lists['id'],
                'g.isSale' => 1,
                'g.isdel' => 1
            ];
            $goods = (new Goods())
                ->alias('g')
                ->join('business b', 'g.businessid= b.id')
                ->whereOr(function ($query) use ($where) {
                    $query->where($where);
                })->field('g.id,g.title,g.images,g.recomm,g.goodspj')
                ->order(['g.sorts' => 'desc', 'b.sort' => 'desc', 'g.recomm' => 'desc', 'g.goodspj' => 'desc', 'g.sale' => 'desc'])
                ->limit(3)
                ->select();
            foreach ($goods as $good) {
                //查询所有评价
                $pj = (new Compent())->where('goodsid', $good['id'])->count();
                if ($pj > 0) {
                    $good['goodspj'] = floor($good['goodspj'] * 10000 / $pj) / 100;
                } else {
                    $good['goodspj'] = 0;
                }
                $good['goodspj'] = $good['goodspj'] > 100 ? 100 : $good['goodspj'];
                $good['goods'] = (new GoodsSpec())->where('goodid', $good['id'])->order('is_default desc')->find();
                $good['images'] = json_decode($good['images'], true);
            }
            $lists['goods'] = $goods;
        }
        //获取下级子菜单
        $this->result($list, 0, '获取成功');
    }

    public function getsonclass()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new PlatSons())->where('isshow', 1)->where('platclassid', $id)->field('created,platclassid,sort,isshow', true)->order('sort desc')->select();
        $this->result($list, 0, '获取成功');
    }

    public function banner()
    {
        $xiaoqu = $this->request->get('xiaoquid/d', 0);
        $types = $this->request->get('types/d', 0);
        $list = (new Banner())->where(['types' => $types, 'xiaoquid' => [0, $xiaoqu]])->field('id,title,url')->select();
        $this->result($list, 0, '获取成功');
    }


    //本地商家
    public function goodslist()
    {
        $data = $this->request->get();
        $xiaoquid = $this->request->get('xiaoquid', 0);
        $businessid = (new BusinessCommu())->where('status', 1)->where('commuid', $xiaoquid)->column('businessid') ?? [];
        if (empty($businessid)) {
            $businessid = [0];
        }
        $business = (new Business())->where(['type' => 1, 'status' => 1, 'id' => $businessid])->column('id');
        $where = [
            ['b.status', '=', 1],
            ['g.isSale', '=',  1],
            ['g.isdel', '=', 1],
            ['g.businessid', 'in', $business]
        ];
        //分类查询
        if (!empty($data['class'])) {
            $where[] = ['g.classid', '=', $data['class']];
        }
        //子分类查询
        if (!empty($data['sons'])) {
            $where[] = ['g.sonsid', '=', $data['sons']];
        }
        if (!empty($data['title'])) {
            $where[] = ['g.title|b.title|g.keywords', 'like', '%' . $data['title'] . '%'];
        }
        $list = (new Goods())
            ->alias('g')
            ->distinct(true)
            ->join('business b', 'g.businessid= b.id');
        $list = $list->whereOr(function ($query) use ($where) {
            $query->where($where);
        })->field('g.id,g.title,g.images,g.recomm,g.descs,g.sale,g.goodspj,b.id as businessid,b.title as btitle');
        //排序
        $data['sort'] = $data['sort'] ?? 0;
        switch ($data['sort']) {
            case '1':
                $list = $list->order(['g.sale' => 'desc']);
                break;
            case '3':
                $list = $list->order(['g.sorts' => 'desc', 'g.recomm' => 'desc']);
                break;
            default:
                $list = $list->order(['g.sorts' => 'desc', 'g.goodspj' => 'desc', 'g.sale' => 'desc']);
                break;
        }
        $list = $list->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $good) {
            //查询所有评价
            $pj = (new Compent())->where('goodsid', $good['id'])->count();
            if ($pj > 0) {
                $good['goodspj'] = floor($good['goodspj'] * 10000 / $pj) / 100;
            } else {
                $good['goodspj'] = 100;
            }
            $good['goodspj'] = $good['goodspj'] > 100 ? 100 : $good['goodspj'];
            $good['images'] = json_decode($good['images'], true);
            $good['goodspec'] = (new GoodsSpec())->field('id,price,name,stock,unmit')->where(['isdel' => 1, 'goodid' => $good['id']])->order('is_default desc')->select();
        }
        $this->result($list, 0, '获取成功');
    }

    public function goodsdetail()
    {
        $goodsid = $this->request->get('goodsid/d', 0);
        $xiaoquid = $this->request->get('xiaoquid/d', 0);
        $good = (new Goods())->field('created', true)->where(['isdel' => 1])->where('id', $goodsid)->find();
        if ($good) {
            $good['canfw'] = 1; //能够服务
            $business = (new Business())->where(['id' => $good['businessid']])->find();
            $bcommu = (new BusinessCommu())->where('status', 1)->where('commuid', $xiaoquid)->find();
            if (empty($business) || $business['status'] != 1 || $business['shows'] != 1 || empty($bcommu)) {
                $good['canfw'] = 0;
            }
            $good['cate_name'] = (new PlatClass())->where('id', $good['classid'])->value('name') ?? '';
            if (!empty($good['sonsid'])) {
                $sons_name = (new PlatSons())->where('id', $good['sonsid'])->value('name') ?? '';
                if (!empty($sons_name)) {
                    $good['cate_name'] = $good['cate_name'] . '(' . $sons_name . ')';
                }
            }
            $fwtime = $business['fwtime'] ?? '00:00 - 24:00';
            $fwtime = explode('-', $fwtime);
            $good['fwtime'] = $fwtime;
            $good['mobile'] = $business['mobile'] ?? '';
            $start = $fwtime[0] ?? '00:00';
            $end = $fwtime[1] ?? '22:00';
            //最早时间计算
            $zuizao = date('H', time() + 1800 + $good['times'] * 60) . ':00';
            //如果超越了营业时间可预约明天
            if (strtotime($zuizao) > strtotime($end)) {
                $zuizao = date('Y-m-d ', time() + 86400) . $start;
            } else {
                $zuizao = date('Y-m-d ') . $zuizao;
            }
            $good['business_name'] = $business['title'] ?? '';
            $good['businesstype'] = $business['type'] ?? 1;
            $good['zuizao'] = $zuizao;
            $images = json_decode($good['images'], true);
            $good['images'] = $images;
            $imagelist = [];
            foreach ($images as $image) {
                $imagelist[] = ['url' => $image];
            }
            $good['imagelist'] = $imagelist;
            $good['parpam'] = json_decode($good['parpam'], true);
            $good['goodspec'] = (new GoodsSpec())->field('id,price,name,stock,unmit,is_default')->where(['isdel' => 1, 'goodid' => $good['id']])->order('is_default desc')->select();
        }
        $this->result($good, 0, '获取成功');
    }


    public function fjgoodslist()
    {
        $data = $this->request->get();
        $lat = $this->request->get('lat', 0);
        $lon = $this->request->get('lng', 0);
        $businessarr = getlatlon($lat, $lon);
        //划分订单
        $where0 = [
            ['b.status', '=', 1],
            ['g.isSale', '=',  1],
            ['g.isdel', '=', 1],
            ['g.type', '=', 1],
        ];
        //街道订单
        $where = [
            ['b.status', '=', 1],
            ['g.isSale', '=',  1],
            ['g.isdel', '=', 1],
            ['g.type', '=', 1],
        ];
        //区域订单
        $where1 = [
            ['b.status', '=', 1],
            ['g.isSale', '=',  1],
            ['g.isdel', '=', 1],
            ['g.type', '=', 1],
        ];
        //城市订单
        $where2 = [
            ['b.status', '=', 1],
            ['g.isSale', '=',  1],
            ['g.isdel', '=', 1],
            ['g.type', '=', 1],
        ];
        //全国订单
        $where3 = [
            ['b.status', '=', 1],
            ['g.isSale', '=',  1],
            ['g.isdel', '=', 1],
            ['g.type', '=', 1],
        ];
        if (!empty($data['title'])) {
            $where0[] = ['g.title|b.title|g.keywords', 'like', '%' . $data['title'] . '%'];
            $where[] = ['g.title|b.title|g.keywords', 'like', '%' . $data['title'] . '%'];
            $where1[] = ['g.title|b.title|g.keywords', 'like', '%' . $data['title'] . '%'];
            $where2[] = ['g.title|b.title|g.keywords', 'like', '%' . $data['title'] . '%'];
            $where3[] = ['g.title|b.title|g.keywords', 'like', '%' . $data['title'] . '%'];
        }
        $list = (new Goods())
            ->alias('g')
            ->distinct(true)
            ->join('business b', 'g.businessid= b.id');
        $street = $this->mygetstreet($data);
        if (!empty($street)) {
            $list =  $list->join('business_area ba', 'b.id= ba.businessid');
            $street = (new Region())->where(['id' => $street, 'level' => 4])->find();
            $area = (new Region())->where(['area_code' => $street['area_code'], 'level' => 3])->find();
            $city = (new Region())->where(['id' => $area['parent_id'], 'level' => 2])->find();
            if (empty($businessarr)) {
                $where0[] = ['g.businessid', 'in', $businessarr];
            }
            $where0[] = ['ba.type', '=',  5];
            $where[] = ['ba.street', '=', $street['id'] ?? 0];
            $where[] = ['ba.type', '=',  4];
            $where1[] = ['ba.area', '=', $street['area_code'] ?? 0];
            $where1[] = ['ba.type', '=',  3];
            $where2[] = ['ba.city', '=', $city['area_code'] ?? 0];
            $where2[] = ['ba.type', '=',  2];
            $where3[] = ['ba.type', '=',  1];
        }
        $list = $list->whereOr(function ($query) use ($where0) {
            $query->where($where0);
        })->whereOr(function ($query) use ($where) {
            $query->where($where);
        })->whereOr(function ($query) use ($where1) {
            $query->where($where1);
        })->whereOr(function ($query) use ($where2) {
            $query->where($where2);
        })->whereOr(function ($query) use ($where3) {
            $query->where($where3);
        })->field('g.id,g.title,g.images,g.descs,b.id as businessid,b.title as btitle,times,g.starbuy');
        //排序
        $data['sort'] = $data['sort'] ?? 0;
        switch ($data['sort']) {
            case '1':
                $list = $list->order(['g.sale' => 'desc']);
                break;
            case '3':
                if (!empty($data['type']) && $data['type'] == 5) {
                    $list = $list->where(['g.sorts' => 'desc', 'g.recomm' => '2']);
                } else {
                    $list = $list->order(['g.sorts' => 'desc', 'g.recomm' => 'desc']);
                }
                break;
            default:
                $list = $list->order(['g.sorts' => 'desc', 'g.goodspj' => 'desc', 'g.sale' => 'desc']);
                break;
        }
        $list = $list->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $good) {
            $good['images'] = json_decode($good['images'], true);
            $good['goodspec'] = (new GoodsSpec())->field('id,price,name,stock,unmit')->where(['isdel' => 1, 'goodid' => $good['id']])->order('is_default desc')->select();
        }
        $this->result($list, 0, '获取成功');
    }


    public function fjsf()
    {

        $businessid = $this->request->get('businessid/d', 0);
        $lat = $this->request->get('lat/f', 0);
        $lon = $this->request->get('lng/f', 0);
        $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $result = (new Recpeople())
            ->field('id,name,lat,lon,mobile,business,' . $filed)
            ->limit(40)
            ->order('dist asc')->where('status', 1);
        if (!empty($businessid)) {
            $result = $result->where(['business' => $businessid]);
        }
        $result = $result->select();
        foreach ($result as $row) {
            $row['star'] = 5;
            $row['order'] = 0;
            //查询所有订单
            $orders = (new Order())->where(['status' => [2, 3, 4]])->where('putorder', $row['id'])->column('id');
            $row['order'] = count($orders);
            $stars = (new Compent())->where(['orderid' => $orders, 'star' => [3, 4, 5]])->avg('star');
            if ($stars <= 3.5 && $stars > 0) {
                $row['star'] = 3.5;
            } elseif ($stars > 0) {
                $row['star'] = $stars;
            }
            $row['sjname'] = (new Business())->where('id', $row['business'])->value('title');
            $tjproduct = (new Goods())->field('id,title,images,descs,times,starbuy')->orderRaw('rand()')->where(['businessid' => $row['business'], 'type' => 1, 'isSale' => 1, 'isdel' => 1])->limit(3)->select();
            foreach ($tjproduct as $goods) {
                $goods['images'] = json_decode($goods['images'], true) ?? [];
                $goods['goodspec'] = (new GoodsSpec())->field('id,price,name,stock,unmit')->where(['isdel' => 1, 'goodid' => $goods['id']])->order('is_default desc')->select();
            }

            $row['tjproduct'] = $tjproduct;
        }
        $this->result($result, 0, '获取成功');
    }
}
